package org.uiot.protocol.group

import org.uiot.protocol.PacketTraits

class Sequence implements SequenceTraits {

    /**
     * 隶属（结构/编组）代码（Hex）
     */
    String hexParentCode
    /**
     * （基础）规则代码
     */
    String ruleCode

    boolean enabled = false

    String remark
    Date dateCreated
    Date lastUpdated

    static constraints = {
        part(nullable: false, inList: PacketTraits.Part.values().toList())
        parentType(nullable: true, inList: Subjection.values().toList(), validator: { val, obj, errors ->
            if (obj.part == PacketTraits.Part.Body && val == null) {
                errors.rejectValue("part", "Properties of parent must be set when 'Part.Body' is selected")
            } else if (obj.part != PacketTraits.Part.Body && val != null) {
                errors.rejectValue("part", "Properties of parent must be NULL when 'Part.Header' or 'Part.Checking' is selected")
            }
        })
        hexParentCode(blank: true, matches: /[a-fA-F0-9]+/)
        serialNo(nullable: false, min: 1)
        dataIdentifier(blank: false, matches: /[a-zA-Z0-9]+/)
        name(blank: false)
        ruleCode(blank: true, unique: [ "part", "parentType", "hexParentCode" ], matches: /[a-zA-Z0-9]+/)
        enabled(blank: false)
        remark(nullable: true, widget: 'textarea')
        dateCreated()
        lastUpdated()
    }

    static mapping = {
        remark type: 'text'
        sort serialNo: "asc"
    }

    def asType(Class target) {
        if (target == CachedSequence) {
            return new CachedSequence(
                    part, parentType, (hexParentCode ? Integer.parseInt(hexParentCode, 16) : null),
                    serialNo, dataIdentifier, name, ruleCode
            )
        }
        throw new ClassCastException("CodecRule cannot be coerced into $target")
    }
}
